package blog.controller;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import blog.entity.Article;
import blog.entity.Comment;
import blog.entity.User;
import blog.service.ArticleService;
import blog.service.CommentService;
import blog.service.UserService;
import blog.utils.DESUtil;
import blog.utils.ImageUtil;
import blog.utils.IpUtil;
import blog.utils.RandomValidateCode;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Resource(name = "userServiceImpl")
	private UserService userService;
	
	@Resource(name = "articleServiceImpl")
	private ArticleService articleService;
	
	@Resource
	private CommentService commentService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request) {
		String str = request.getParameter("userName");
		String password = request.getParameter("userPass");
		String checkCode = request.getParameter("checkCode").toUpperCase();
		String CheckCode=(String)request.getSession().getAttribute(RandomValidateCode.RANDOMCODEKEY);
		if(!checkCode.equals(CheckCode.toUpperCase())) {
			request.setAttribute("msg", "验证码错误");
			return "login";
		}
		User user = userService.getUserByNameOrEmail(str);
		if (user != null) {
			if (DESUtil.encrypt(password).equals(user.getUserPass())) {
				request.getSession().setAttribute("session_user", user);
				User nowUser=new User();
				nowUser.setUserLastLoginTime(LocalDateTime.now());
				nowUser.setUserLastLoginIp(IpUtil.getIp(request));
				nowUser.setUserId(user.getUserId());
				userService.updateUser(nowUser);
				return show(request);
			} else {
				request.setAttribute("msg", "密码错误");
				return "login";
			}
		} else {
			request.setAttribute("msg", "账号错误");
			return "login";
		}
	}
	
	/**
	 * 更新session防止突然掉线
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/time", method = RequestMethod.POST)
	public void time(HttpServletRequest request,HttpServletResponse response) {
		//提出放回session，防止突然掉线
		User admin=(User) request.getSession().getAttribute("session_user");
		request.getSession().setAttribute("session_user", admin);
	}
	
	/**
	 * 主页面显示
	 * @param request
	 * @return
	 */
	private String show(HttpServletRequest request) {
		//查询最近的前5条文章
		List<Article> articleList=	articleService.listRecentArticle(5);
		request.setAttribute("articleList", articleList);
		
		//查询最近的前5条评论
		List<Comment> commentList=commentService.listRecentComment(5);
		request.setAttribute("commentList", commentList);
		return "index";
	}
	
	/**
	 * 进入后台页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "index")
	public String index(HttpServletRequest request){
		return show(request);	
	}
	/**
	 * 用户管理页
	 * @param m
	 * @return
	 */
	@RequestMapping("")
	public String listUser(ModelMap m) {
		List<User> userList=userService.ListUser();
		m.put("userList", userList);
		return "User/user-list";
	}
	
	/**
	 * 获取生成验证码显示到 UI 界面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value="/checkCode")
	public void checkCode(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
		//设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        
        //设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response);//输出图片方法
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
	
	/**
	 *退出登陆
	 *
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().invalidate();
		response.sendRedirect("login");
	}
	
	/**
	 * 进入用户添加页面
	 * @return
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String gotoAddPage() {
		return "User/user-add";
	}
	/**
	 * 用户添加转跳
	 * @param user
	 * @param photo
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public String add(@Validated User user,BindingResult bResult, MultipartFile photo,ModelMap m) throws IOException {
		if(bResult.hasErrors()) {
			List<ObjectError> errList =bResult.getAllErrors();
			for(ObjectError e:errList) {
				System.out.println(e.getDefaultMessage());
			}	
			m.put("msg","校验没通过,用户添加失败");
			m.put("errList", errList);
		}else {
			user.setUserPass(DESUtil.encrypt(user.getUserPass()));
			user.setUserRegisterTime(LocalDateTime.now());
			user.setUserPhoto(ImageUtil.resizeImage(photo.getBytes(),100,"jpg"));
			userService.add(user);
		}
		
		
		return "forward:/user";
}
	/**
	 * 传递用户图片
	 */
	@RequestMapping("/photo/{userId}")
	public void getPhoto(@PathVariable("userId") Integer userId, HttpServletResponse response ) throws IOException {
		User  user=userService.getUserById(userId);
		response.setContentType("image/jpg");
		ServletOutputStream outStream =response.getOutputStream();
		if(user.getUserPhoto()!=null) {
		outStream.write(user.getUserPhoto());
		}
		outStream.flush();
	}
	
	/**
	 * 删除用户
	 */
	@RequestMapping("/delete/{userId}")
	public String delete(@PathVariable("userId") Integer userId, HttpServletResponse response ) throws IOException {
		userService.deleteUserById(userId);
		return "forward:/user";
	}
}
